package com.example.helloword.ui.recyclerview;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class BindingToRecyclerviewAdapter extends RecyclerView.Adapter {

    private List items;
    private int layoutId;
    private int brId;
    private ItemClickListener itemClickListener;

    public BindingToRecyclerviewAdapter(List items, int layoutId, int brId) {
        this.items = items;
        this.layoutId = layoutId;
        this.brId = brId;
    }

    public void setItems(List items) {
        this.items = items;
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        ViewDataBinding binding = DataBindingUtil.inflate(inflater, layoutId, parent, false);
//        Log.v("onCreateViewHolder","");

        return new Holder(binding);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ViewDataBinding binding = ((Holder) holder).getBinding();
        binding.setVariable(brId,items.get(position));
        if (itemClickListener!=null)
        itemClickListener.setClickEvent(binding,position);
//        Log.v("onBindViewHolder",items.get(position).toString());
//        binding.executePendingBindings();

    }

    @Override
    public int getItemCount() {
        return items == null ? 0 : items.size();
    }




    class  Holder extends RecyclerView.ViewHolder{
        private ViewDataBinding binding;

        public ViewDataBinding getBinding() {
            return binding;
        }

        public Holder(@NonNull ViewDataBinding binding) {
            super(binding.getRoot());
            this.binding=binding;
        }
    }

    public interface ItemClickListener{
        public void setClickEvent(ViewDataBinding binding,int position);
    }
}
